<template>
  <div class="admin-dashboard-container">
    <h2>管理后台概览</h2>
    
    <!-- 加载中提示 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <!-- 数据统计卡片 -->
    <el-row :gutter="20" v-if="!loading">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-card-inner">
            <div class="card-icon sales-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">总销售额</div>
              <div class="card-value">¥{{ formatNumber(salesData.totalSales ?? 0) }}</div>
              <div class="card-footer">最近7天</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-card-inner">
            <div class="card-icon orders-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">订单总数</div>
              <div class="card-value">{{ ordersData.totalOrders ?? 0 }}</div>
              <div class="card-footer">最近7天</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-card-inner">
            <div class="card-icon products-icon">
              <el-icon><Goods /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">商品总数</div>
              <div class="card-value">{{ productsData.totalProducts ?? 0 }}</div>
              <div class="card-footer">全部商品</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-card-inner">
            <div class="card-icon avg-icon">
              <el-icon><PriceTag /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">日均销售额</div>
              <div class="card-value">¥{{ formatNumber(salesData.averageDailySales || 0) }}</div>
              <div class="card-footer">最近7天</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 销售趋势图表 -->
    <el-row :gutter="20" class="chart-row" v-show="!loading">
      <el-col :xs="24" :sm="24" :md="16" :lg="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
              <el-radio-group v-model="salesDateRange" size="small" @change="fetchSalesData">
                <el-radio-button label="7">最近7天</el-radio-button>
                <el-radio-button label="30">最近30天</el-radio-button>
                <el-radio-button label="90">最近90天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="salesChartRef"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>支付方式占比</span>
            </div>
          </template>
          <div class="chart-container" ref="paymentChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 热销商品和渠道销售排行 -->
    <el-row :gutter="20" class="chart-row" v-show="!loading">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>热销商品排行</span>
              <el-radio-group v-model="productsDateRange" size="small" @change="fetchProductsData">
                <el-radio-button label="7">最近7天</el-radio-button>
                <el-radio-button label="30">最近30天</el-radio-button>
                <el-radio-button label="90">最近90天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <el-table :data="productsData.topProducts || []" stripe style="width: 100%" max-height="400">
            <el-table-column label="排名" width="60" align="center">
              <template #default="scope">
                <span class="rank-badge" :class="getRankClass(scope.$index + 1)">
                  {{ scope.$index + 1 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" min-width="120" />
            <el-table-column prop="quantity" label="销售数量" width="100" align="center" />
            <el-table-column prop="amount" label="销售金额" width="120" align="right">
              <template #default="scope">
                ¥{{ formatNumber(scope.row.amount) }}
              </template>
            </el-table-column>
            <template #empty>
              <div style="padding: 20px; text-align: center; color: #999;">
                <p>暂无销售数据</p>
                <p style="font-size: 12px;">总商品数: {{ productsData.totalProducts || 0 }}</p>
              </div>
            </template>
          </el-table>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card shadow="hover" class="chart-card channel-chart-card">
          <template #header>
            <div class="card-header">
              <span>渠道销售排名</span>
              <div>
                <el-radio-group v-model="channelTimeRange" size="small" style="margin-right: 10px;" @change="fetchChannelData">
                  <el-radio-button label="7">最近7天</el-radio-button>
                  <el-radio-button label="30">最近30天</el-radio-button>
                  <el-radio-button label="month">按月</el-radio-button>
                </el-radio-group>
                <el-date-picker 
                  v-if="channelTimeRange === 'month'" 
                  v-model="selectedMonth" 
                  type="month" 
                  size="small" 
                  placeholder="选择月份" 
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                  @change="fetchChannelData"
                  style="width: 120px; margin-right: 10px;"
                />
                <el-radio-group v-model="channelSortType" size="small" @change="updateChannelChart">
                  <el-radio-button label="amount">按销售额</el-radio-button>
                  <el-radio-button label="count">按订单数</el-radio-button>
                  <el-radio-button label="average">按均单价</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="channelChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { Money, Document, Goods, PriceTag } from '@element-plus/icons-vue'
import axios from 'axios'
import api from '@/utils/api'
import * as echarts from 'echarts'

// 常量定义
const CHART_CONFIG = {
  RETRY_DELAY: 100,
  MAX_RETRIES: 3,
  CHART_HEIGHT: 300,
  MAX_CHANNELS_DISPLAY: 5,
  DEFAULT_COLORS: [
    '#409EFF', '#67C23A', '#E6A23C', '#F56C6C',
    '#909399', '#9B59B6', '#3498DB', '#1ABC9C',
    '#27AE60', '#F1C40F', '#E67E22', '#E74C3C'
  ]
}

// 数据响应式变量
const loadingStates = ref({
  sales: false,
  orders: false,
  products: false,
  channels: false
})

// 计算总loading状态
const loading = computed(() =>
  Object.values(loadingStates.value).some(loading => loading)
)

const salesData = ref({})
const ordersData = ref({})
const productsData = ref({})
const channelData = ref({})
// 独立的时间范围管理
const salesDateRange = ref('7')
const ordersDateRange = ref('7')
const productsDateRange = ref('30') // 产品数据默认30天
const channelTimeRange = ref('7')
const channelSortType = ref('amount') // 渠道排序类型：amount, count, average
const selectedMonth = ref(null)

// 图表引用
const salesChartRef = ref(null)
const paymentChartRef = ref(null)
const channelChartRef = ref(null)

// 图表实例
let salesChart = null
let paymentChart = null
let channelChart = null

// 统一错误处理函数
const handleApiError = (error, context) => {
  console.error(`${context}失败:`, error)
  console.error('错误详情:', error.response?.data)

  // 如果是401错误，跳转到登录页
  if (error.response?.status === 401) {
    console.log('认证失败，跳转到登录页')
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    window.location.href = '/login'
    return true // 表示已处理401错误
  }
  return false
}

// 格式化数字，加千位分隔符
const formatNumber = (num) => {
  return parseFloat(num).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
}

// 获取排名样式类
const getRankClass = (rank) => {
  if (rank === 1) return 'rank-first'
  if (rank === 2) return 'rank-second'
  if (rank === 3) return 'rank-third'
  return 'rank-normal'
}

// 获取销售数据
const fetchSalesData = async () => {
  try {
    console.log('开始获取销售数据，天数:', salesDateRange.value)
    loadingStates.value.sales = true
    const { data } = await api.get('/dashboard/sales?days=' + salesDateRange.value)
    console.log('销售数据API响应:', data)
    salesData.value = data.data
    console.log('更新后的salesData:', salesData.value)
  } catch (error) {
    if (!handleApiError(error, '获取销售数据')) {
      // 如果不是401错误，显示其他错误信息
      console.error('获取销售数据失败:', error)
    }
  } finally {
    loadingStates.value.sales = false
  }
}

// 获取订单数据
const fetchOrdersData = async () => {
  try {
    loadingStates.value.orders = true
    const { data } = await api.get('/dashboard/orders?days=' + ordersDateRange.value)
    ordersData.value = data.data
  } catch (error) {
    handleApiError(error, '获取订单数据')
  } finally {
    loadingStates.value.orders = false
  }
}

// 获取产品数据
const fetchProductsData = async () => {
  try {
    console.log('开始获取产品数据，天数:', productsDateRange.value)
    loadingStates.value.products = true
    const { data } = await api.get('/dashboard/products?days=' + productsDateRange.value)
    console.log('产品数据API响应:', data)
    productsData.value = data.data
    console.log('更新后的productsData:', productsData.value)
    console.log('商品排行数量:', productsData.value?.topProducts?.length || 0)
  } catch (error) {
    handleApiError(error, '获取产品数据')
  } finally {
    loadingStates.value.products = false
  }
}

// 获取渠道数据
const fetchChannelData = async () => {
  try {
    let url = '/dashboard/channels';
    let params = {};
    
    if (channelTimeRange.value === 'month' && selectedMonth.value) {
      // 按月查询
      params.month = selectedMonth.value;
      params.type = 'month';
    } else {
      // 按天数查询
      params.days = channelTimeRange.value;
    }
    
    // 构建查询字符串
    const queryString = Object.entries(params)
      .map(([key, value]) => `${key}=${value}`)
      .join('&');
    
    loadingStates.value.channels = true
    const { data } = await api.get(`${url}?${queryString}`)
    channelData.value = data.data

    // 渠道图表将在所有数据加载完成后统一渲染
  } catch (error) {
    handleApiError(error, '获取渠道数据')
  } finally {
    loadingStates.value.channels = false
  }
}

// 图表渲染重试函数
const renderChartWithRetry = async (chartRef, renderFn, maxRetries = CHART_CONFIG.MAX_RETRIES) => {
  for (let i = 0; i < maxRetries; i++) {
    await nextTick()
    if (chartRef.value) {
      renderFn()
      return true
    }
    await new Promise(resolve => setTimeout(resolve, CHART_CONFIG.RETRY_DELAY))
  }
  console.warn('图表渲染失败：DOM元素不存在')
  return false
}

// 初始化销售趋势图表
const renderSalesChart = () => {
  if (!salesChartRef.value) {
    return false
  }

  // 初始化图表
  if (!salesChart) {
    salesChart = echarts.init(salesChartRef.value)
  }
  
  // 准备数据
  const dates = salesData.value.salesData?.map(item => item.date) || []
  const amounts = salesData.value.salesData?.map(item => item.amount) || []
  
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />销售额: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        data: amounts,
        areaStyle: {
          opacity: 0.3
        },
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  // 渲染图表
  salesChart.setOption(option)
  return true
}

// 初始化支付方式图表
const renderPaymentChart = () => {
  if (!paymentChartRef.value) {
    return false
  }

  // 初始化图表
  if (!paymentChart) {
    paymentChart = echarts.init(paymentChartRef.value)
  }
  
  // 准备数据
  const paymentMethods = salesData.value.salesByPaymentMethod || {}
  const data = Object.entries(paymentMethods).map(([name, value]) => {
    // 转换支付方式名称
    let displayName = name
    if (name === 'cash') displayName = '现金支付'
    if (name === 'wechat') displayName = '微信支付'
    if (name === 'alipay') displayName = '支付宝支付'
    if (name === 'complimentary') displayName = '招待'
    if (name === 'unknown') displayName = '未知方式'
    
    return { name: displayName, value }
  })
  
  // 计算总金额，用于百分比计算
  const total = data.reduce((sum, item) => sum + item.value, 0);
  
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '支付方式',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: (params) => {
            // 计算百分比
            const percent = ((params.value / total) * 100).toFixed(1);
            return `${percent}%`;
          },
          position: 'inside',
          fontSize: 12,
          fontWeight: 'bold'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold',
            formatter: (params) => {
              const percent = ((params.value / total) * 100).toFixed(1);
              return `${params.name}\n¥${formatNumber(params.value)}\n${percent}%`;
            }
          }
        },
        labelLine: {
          show: false
        },
        data
      }
    ]
  }
  
  // 渲染图表
  paymentChart.setOption(option)
  return true
}

// 初始化渠道排名图表
const renderChannelChart = () => {
  if (!channelChartRef.value) {
    return false
  }

  // 初始化图表
  if (!channelChart) {
    channelChart = echarts.init(channelChartRef.value)
  }

  return updateChannelChart()
}

// 更新渠道排名图表数据
const updateChannelChart = () => {
  if (!channelChart || !channelData.value || !channelData.value.channelSales) {
    return false
  }
  
  // 获取渠道数据，过滤掉无销售额的渠道
  let channels = [...channelData.value.channelSales]
    .filter(item => item.totalAmount > 0)
  
  // 根据排序类型处理数据
  if (channelSortType.value === 'count') {
    channels.sort((a, b) => b.orderCount - a.orderCount)
  } else if (channelSortType.value === 'average') {
    channels.sort((a, b) => b.averageAmount - a.averageAmount)
  } else {
    // 默认按销售额排序
    channels.sort((a, b) => b.totalAmount - a.totalAmount)
  }
  
  // 限制最多显示渠道数量，防止图表过于拥挤
  channels = channels.slice(0, CHART_CONFIG.MAX_CHANNELS_DISPLAY)
  
  // 准备数据
  const names = channels.map(item => item.name)
  let values = []
  let tooltipFormatter = ''
  
  if (channelSortType.value === 'count') {
    values = channels.map(item => item.orderCount)
    tooltipFormatter = '{b}<br />订单数量: {c} 笔<br />销售额: ¥{@amount}<br />均单价: ¥{@average}'
  } else if (channelSortType.value === 'average') {
    values = channels.map(item => item.averageAmount)
    tooltipFormatter = '{b}<br />均单价: ¥{c}<br />订单数量: {@count} 笔<br />销售额: ¥{@amount}'
  } else {
    values = channels.map(item => item.totalAmount)
    tooltipFormatter = '{b}<br />销售额: ¥{c}<br />订单数量: {@count} 笔<br />均单价: ¥{@average}'
  }
  
  // 准备自定义系列数据
  const seriesData = channels.map(item => ({
    value: channelSortType.value === 'count' 
      ? item.orderCount 
      : (channelSortType.value === 'average' ? item.averageAmount : item.totalAmount),
    amount: item.totalAmount.toFixed(2),
    count: item.orderCount,
    average: item.averageAmount.toFixed(2)
  }))
  
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const param = params[0]
        const value = param.value
        const dataIndex = param.dataIndex
        const data = seriesData[dataIndex]
        
        return tooltipFormatter
          .replace('{b}', param.name)
          .replace('{c}', channelSortType.value === 'count' 
            ? value 
            : formatNumber(value))
          .replace('{@amount}', formatNumber(data.amount))
          .replace('{@count}', data.count)
          .replace('{@average}', formatNumber(data.average))
      }
    },
    grid: {
      left: '10%',
      right: '5%',
      bottom: '15%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: names,
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        interval: 0,
        rotate: 45, // 更大的旋转角度
        fontSize: 10 // 更小的字体
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: channelSortType.value === 'count'
          ? '{value}'
          : '¥{value}'
      }
    },
    series: [
      {
        name: channelSortType.value === 'count' 
          ? '订单数量' 
          : (channelSortType.value === 'average' ? '均单价' : '销售额'),
        type: 'bar',
        data: seriesData,
        label: {
          show: true,
          position: 'top',
          formatter: (params) => {
            return channelSortType.value === 'count'
              ? `${params.value} 笔`
              : `¥${formatNumber(params.value)}`
          }
        },
        itemStyle: {
          // 为每个渠道分配不同颜色
          color: (params) => {
            return CHART_CONFIG.DEFAULT_COLORS[params.dataIndex % CHART_CONFIG.DEFAULT_COLORS.length]
          }
        }
      }
    ]
  }
  
  // 渲染图表
  channelChart.setOption(option)
  return true
}

// 渲染所有图表
const renderAllCharts = async () => {
  console.log('开始渲染所有图表...')
  await nextTick()

  // 等待DOM完全更新
  setTimeout(async () => {
    console.log('DOM元素状态:', {
      salesChart: !!salesChartRef.value,
      paymentChart: !!paymentChartRef.value,
      channelChart: !!channelChartRef.value
    })

    if (salesData.value && Object.keys(salesData.value).length > 0) {
      await renderChartWithRetry(salesChartRef, renderSalesChart)
      await renderChartWithRetry(paymentChartRef, renderPaymentChart)
    }

    if (channelData.value && channelData.value.channelSales) {
      await renderChartWithRetry(channelChartRef, renderChannelChart)
    }
  }, 200)
}

// 监听loading状态变化，当所有数据加载完成时渲染图表
watch(loading, async (newLoading) => {
  if (!newLoading) {
    console.log('所有数据加载完成，开始渲染图表')
    await renderAllCharts()
  }
})

// 监听销售数据变化，重新渲染销售相关图表
watch(salesData, async (newSalesData) => {
  console.log('salesData监听器触发，新数据:', newSalesData)
  if (newSalesData && Object.keys(newSalesData).length > 0) {
    console.log('销售数据更新，重新渲染图表，DOM元素状态:', {
      salesChartRef: !!salesChartRef.value,
      paymentChartRef: !!paymentChartRef.value,
      loading: loading.value
    })

    // 等待多个tick确保DOM完全更新
    await nextTick()
    await nextTick()

    // 增加延时，确保DOM引用恢复
    setTimeout(async () => {
      console.log('延时后DOM元素状态:', {
        salesChartRef: !!salesChartRef.value,
        paymentChartRef: !!paymentChartRef.value
      })

      if (salesChartRef.value && paymentChartRef.value) {
        console.log('开始重新渲染销售图表')
        const salesResult = await renderChartWithRetry(salesChartRef, renderSalesChart)
        console.log('销售图表渲染结果:', salesResult)

        console.log('开始重新渲染支付图表')
        const paymentResult = await renderChartWithRetry(paymentChartRef, renderPaymentChart)
        console.log('支付图表渲染结果:', paymentResult)
      } else {
        console.warn('DOM元素引用仍然丢失，尝试重新获取')
        // 尝试通过全局渲染来恢复
        await renderAllCharts()
      }
    }, 300)
  }
}, { deep: true })

// 监听渠道数据变化，重新渲染渠道图表
watch(channelData, async (newChannelData) => {
  if (newChannelData && newChannelData.channelSales) {
    console.log('渠道数据更新，重新渲染图表')
    await nextTick()
    setTimeout(async () => {
      await renderChartWithRetry(channelChartRef, renderChannelChart)
    }, 100)
  }
}, { deep: true })

// 监听产品数据变化
watch(productsData, (newProductsData) => {
  if (newProductsData && newProductsData.topProducts) {
    console.log('产品数据更新，商品数量:', newProductsData.topProducts.length)
  }
}, { deep: true })

// 窗口大小改变时重绘图表
const handleResize = () => {
  salesChart?.resize()
  paymentChart?.resize()
  channelChart?.resize()
}

// 组件挂载时获取数据
onMounted(() => {
  // 检查登录状态
  const token = localStorage.getItem('token');
  if (!token) {
    window.location.href = '/login';
    return;
  }

  // 设置默认月份为当前月份
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  selectedMonth.value = `${year}-${month}`;

  // 获取数据
  fetchSalesData();
  fetchOrdersData();
  fetchProductsData();
  fetchChannelData();
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
})

// 组件卸载时销毁图表实例
onUnmounted(() => {
  salesChart?.dispose()
  paymentChart?.dispose()
  channelChart?.dispose()
  
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.admin-dashboard-container {
  padding: 20px;
}

.loading-container {
  margin: 20px 0;
}

.chart-row {
  margin-top: 20px;
}

.data-card {
  height: 120px;
}

.data-card-inner {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.card-icon .el-icon {
  font-size: 24px;
  color: white;
}

.sales-icon {
  background-color: #409EFF;
}

.orders-icon {
  background-color: #67C23A;
}

.products-icon {
  background-color: #E6A23C;
}

.avg-icon {
  background-color: #F56C6C;
}

.card-content {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.card-footer {
  font-size: 12px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card {
  height: 360px;
}

.chart-container {
  height: 300px;
}

.channel-chart-card {
  height: 360px;
}

.channel-chart-card .chart-container {
  height: 300px;
}

.test-links {
  margin-top: 20px;
  margin-bottom: 20px;
}

.test-links h3 {
  font-size: 18px;
  margin-bottom: 10px;
}

.test-links div {
  margin-bottom: 10px;
}

.test-links a {
  color: #409EFF;
  text-decoration: none;
}

/* 排名徽章样式 */
.rank-badge {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 50%;
  font-weight: bold;
  font-size: 12px;
  color: white;
}

.rank-first {
  background: linear-gradient(135deg, #FFD700, #FFA500);
  box-shadow: 0 2px 4px rgba(255, 215, 0, 0.3);
}

.rank-second {
  background: linear-gradient(135deg, #C0C0C0, #A0A0A0);
  box-shadow: 0 2px 4px rgba(192, 192, 192, 0.3);
}

.rank-third {
  background: linear-gradient(135deg, #CD7F32, #B8860B);
  box-shadow: 0 2px 4px rgba(205, 127, 50, 0.3);
}

.rank-normal {
  background: linear-gradient(135deg, #409EFF, #337ECC);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

/* 移动端响应式样式 */
@media (max-width: 768px) {
  .admin-dashboard-container {
    padding: 10px;
  }

  /* 数据卡片在移动端堆叠显示 */
  .el-row .el-col {
    margin-bottom: 15px;
  }

  .data-card {
    height: auto;
    min-height: 100px;
  }

  .data-card-inner {
    padding: 10px;
  }

  .card-icon {
    width: 50px;
    height: 50px;
    margin-right: 10px;
  }

  .card-icon .el-icon {
    font-size: 20px;
  }

  .card-value {
    font-size: 20px;
  }

  /* 图表卡片优化 */
  .chart-card {
    height: auto;
    min-height: 300px;
  }

  .chart-container {
    height: 250px;
  }

  .channel-chart-card {
    height: auto;
    min-height: 300px;
  }

  .channel-chart-card .chart-container {
    height: 250px;
  }

  /* 卡片头部优化 */
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .card-header .el-radio-group {
    width: 100%;
  }

  .card-header .el-radio-button {
    flex: 1;
  }
}

@media (max-width: 480px) {
  .admin-dashboard-container {
    padding: 5px;
  }

  .card-value {
    font-size: 18px;
  }

  .card-title {
    font-size: 12px;
  }

  .chart-container {
    height: 200px;
  }

  .channel-chart-card .chart-container {
    height: 200px;
  }

  /* 表格在移动端的优化 */
  .el-table {
    font-size: 12px;
  }

  .el-table .cell {
    padding: 4px 6px;
  }

  .rank-badge {
    width: 20px;
    height: 20px;
    line-height: 20px;
    font-size: 10px;
  }
}
</style>